package com.ruoyi.StarStudio.Controller;


import com.github.pagehelper.PageInfo;
import com.ruoyi.StarStudio.Entity.*;
import com.ruoyi.StarStudio.Service.GoodsService;
import com.ruoyi.StarStudio.Service.PanicBuyingGoodsService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/pb_goods")
public class PanicBuyingGoodsController  {

    @Autowired
    PanicBuyingGoodsService panicBuyingGoodsService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    RedisCache redisCache;

    /**
     * 带搜索条件分页查询（商家后台端）
     * @param panicBuyingGoods 抢购商品对象
     * @return 结果对象 Result
     */
    @GetMapping("/page")
    public PageResult findPanicBuyingGoodsList(PanicBuyingGoods panicBuyingGoods){
        PageUtils.startPage();
        List<PanicBuyingGoods> panicBuyingGoodsList;
        long totalRecord;
        try {
            panicBuyingGoodsList = panicBuyingGoodsService.findPanicBuyingGoodsList(panicBuyingGoods);
            totalRecord = panicBuyingGoodsService.findTotalRecord();
        } catch (Exception e) {
            e.printStackTrace();
                    return new PageResult(HttpStatusCode.ERROR, MessageConstant.QUERY_PANIC_BUYING_GOODS_FAIL);
        }
        return new PageResult(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PANIC_BUYING_GOODS_SUCCESS,new PageInfo<>(panicBuyingGoodsList).getTotal(),panicBuyingGoodsList, totalRecord);
    }

    /**
     * 带搜索条件查询（APP端）
     * @param panicBuyingGoods 抢购商品对象
     * @return 结果对象 Result
     */
    @GetMapping("/list")
    public Result findPanicBuyingGoodsResultList(PanicBuyingGoods panicBuyingGoods){
        List<PanicBuyingGoods> panicBuyingGoodsList;
        List<GoodsResult> list = null;
        try {
            panicBuyingGoodsList = panicBuyingGoodsService.findPanicBuyingGoodsList(panicBuyingGoods);
            if (panicBuyingGoodsList.size() > 0){
                list = new ArrayList<>();
                for (PanicBuyingGoods pbGoods : panicBuyingGoodsList) {
                    GoodsResult goodsResult = new GoodsResult(goodsService.findByGoods_id(pbGoods.getGoods_id()),pbGoods);
                    if (new Timestamp(new Date().getTime()).before(pbGoods.getPanic_buying_start_time())){
                        goodsResult.setRemainBeginSeconds((int)((pbGoods.getPanic_buying_start_time().getTime() - new Date().getTime())/1000));
                        goodsResult.setRemainEndSeconds((int)((pbGoods.getPanic_buying_end_time().getTime() - new Date().getTime())/1000));
                    }else if (new Timestamp(new Date().getTime()).after(pbGoods.getPanic_buying_end_time())) {
                        goodsResult.setRemainBeginSeconds(-1);
                        goodsResult.setRemainEndSeconds(-1);
                    }else {
                        goodsResult.setRemainBeginSeconds(0);
                        goodsResult.setRemainEndSeconds((int)((pbGoods.getPanic_buying_end_time().getTime() - new Date().getTime())/1000));
                    }
                    list.add(goodsResult);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR, MessageConstant.QUERY_PANIC_BUYING_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.QUERY_PANIC_BUYING_GOODS_SUCCESS,list);
    }

    /**
     * 更新抢购商品信息
     * @param panicBuyingGoods 抢购商品对象
     * @return 结果对象 Result
     */
    @Log(title = "修改抢购商品", businessType = BusinessType.INSERT)
    @PutMapping
    public Result updatePanicBuyingGoods(@RequestBody PanicBuyingGoods panicBuyingGoods){
        try {
            int i = panicBuyingGoodsService.updatePanicBuyingGoods(panicBuyingGoods);
            if (i > 0){
                // 将抢购商品库存更新到 Redis缓存中
                redisCache.setCacheObject("panic_buying_goods:" + panicBuyingGoods.getGoods_id(),panicBuyingGoods.getPanic_buying_goods_stock());
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().equals("商品库存不足！")){
                return new Result(HttpStatusCode.ERROR,MessageConstant.OUT_OF_GOODS_STOCK);
            }
            if (e.getMessage().equals("库存不能小于零！")){
                return new Result(HttpStatusCode.ERROR,MessageConstant.STOCK_CAN_NOT_LESS_THAN_ZERO);
            }
            return new Result(HttpStatusCode.ERROR,MessageConstant.UPDATE_PANIC_BUYING_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.UPDATE_PANIC_BUYING_GOODS_SUCCESS);
    }

    /**
     * 新增抢购商品
     * @param panicBuyingGoods 抢购商品对象
     * @return 结果对象 Result
     */
    @Log(title = "新增抢购商品", businessType = BusinessType.INSERT)
    @PostMapping
    public Result AddPanicBuyingGoods(@RequestBody PanicBuyingGoods panicBuyingGoods){
        try {
            panicBuyingGoodsService.AddPanicBuyingGoods(panicBuyingGoods);
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getMessage().equals("商品库存不足！")){
                return new Result(HttpStatusCode.ERROR,MessageConstant.OUT_OF_GOODS_STOCK);
            }
            return new Result(HttpStatusCode.ERROR,MessageConstant.ADD_PANIC_BUYING_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.ADD_PANIC_BUYING_GOODS_SUCCESS);
    }

    /**
     * 删除抢购商品
     * @param panic_buying_goods_id 抢购商品ID（不是商品ID）
     * @return 结果对象 Result
     */
    @Log(title = "删除抢购商品", businessType = BusinessType.DELETE)
    @DeleteMapping("/{panic_buying_goods_id}")
    public Result DeletePanicBuyingGoods(@PathVariable long panic_buying_goods_id){
        try {
            panicBuyingGoodsService.DeletePanicBuyingGoods(panic_buying_goods_id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(HttpStatusCode.ERROR,MessageConstant.DELETE_PANIC_BUYING_GOODS_FAIL);
        }
        return new Result(HttpStatusCode.SUCCESS,MessageConstant.DELETE_PANIC_BUYING_GOODS_SUCCESS);
    }
}
